class Cart{
constructor(){
    this.url = "http://localhost:3000/api";
    this.cent = document.querySelector(".shopbox");

    this.getLocal();
    this.load();
    this.addEvent();
}
addEvent(){
    const that = this;
    this.cent.addEventListener("input",function(eve){
        const e = eve || window.event;
        const target = e.target || e.srcElement;
        if(target.className === "setNum"){
            that.id = target.parentNode.parentNode.getAttribute("index");
            that.num = target.value-0;
            that.setLocal(function(i){
                that.goods[i].num = that.num;
            });
        }
    })
    this.cent.addEventListener("click",function(eve){
        const e = eve || window.event;
        const target = e.target || e.srcElement;
        if(target.className === "del"){
            that.id = target.parentNode.getAttribute("index");
            target.parentNode.remove();
            that.setLocal(function(i){
                that.goods.splice(i, 1)
            });
        }
    })
}

setLocal(cb){
    let i = 0;
    this.goods.some((val,idx)=>{
        i = idx;
        return val.id === this.id;
    })
    cb(i);
    localStorage.setItem("goods", JSON.stringify(this.goods));
}
getLocal(){
    this.goods = localStorage.getItem("goods") ? JSON.parse(localStorage.getItem("goods")) : [];
}
load(){
    ajax({
        url:this.url,
        data:{
            type:"getGoods"
        },
        success:res=>{
            this.res = JSON.parse(res).msg;
            this.render();
        }
    })
}
render(){
    let str = "";
    this.res.forEach(val1=>{
        this.goods.forEach(val2=>{
            if(val1.proId === val2.id){


                str+=` <div class="shop-cent-2">
                        <input type="checkbox">           
                        <div index="${val2.id} class="cent-right">
                        <img src="${val1.img}" alt="" class="tiaodx">
                        <div class="shangpinmingzi">${val1.proName}</div>
                        <span class="xiugai1">￥${val1.price}</span>
                        <input type="number" id="number1" class="setNum" value="${val2.num}/>

                        <span class="xiugaier">￥${val2.num * val1.price}</span>
                        
                        <span class="shanchu ">删除</span>
                        </div>
                        </div>`

            }
        })
    })
    this.cent.innerHTML = str;
}
}
new Cart();

// require.config({
//     baseUrl:"./",
//     paths:{
//         jq:"./libs/jquery"
//     }
// })

